import 'package:flutter/material.dart';
import 'registerPage.dart';
import 'package:groovin_material_icons/groovin_material_icons.dart';
import 'package:app_happy_flutter/code/Tool/NetHttp/net.dart';
import 'package:app_happy_flutter/code/Tool/NetHttp/net_url.dart';
import 'package:app_happy_flutter/code/Tool/NetHttp/md5.dart';
import 'app_route.dart';///全局路由
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  String _email, _password;
  bool _isObscure = true;
  Color _eyeColor;
  List _loginMethod = [
    {
      "title": "微信",
      "icon": GroovinMaterialIcons.wechat,
    },
    {
      "title": "QQ",
      "icon": GroovinMaterialIcons.qqchat,
    },
    {
      "title": "Apple ID",
      "icon": GroovinMaterialIcons.apple,
    },
  ];

  ///登录按钮点击事件（执行登录方法）
  void validateAndSave(){

    final form = _formKey.currentState;

    //收起键盘
    FocusScope.of(context).requestFocus(FocusNode());

    if(form.validate()){
      ///只有输入的内容符合要求通过才会到达此处
     Net().get(NetUrl.Token_Url,null,success: (response){
       Map map = response;
       //去登陆
       toLogin(map["result"]);
     },failure: (error){

     });
    }
    else{
      ///验证不通过

    }
  }

  //执行登录验证
  void toLogin(String token) {

    final form = _formKey.currentState;

    if(form.validate() && token.length > 0) {
      ///只有输入的内容符合要求通过才会到达此处
      String psw = MD5.aesPassword(_email,_password, token);

      Map<String,dynamic> parame = {"token":token,"username":_email,"password":psw,"ismobile":"true","rememberMe":"true"};

      Net().post(NetUrl.LOGIN_USER,parame,success: (response){

        // 登录成功后跳转到页面
        Navigator.pushNamed(context, RoutePath.todoTabBar);
     },failure: (error){

     });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background.png"),
            fit: BoxFit.cover,
            ),
        ),


        child: Form(
            key: _formKey,
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 22.0),
              physics: const NeverScrollableScrollPhysics(),
              children: <Widget>[
                SizedBox(height: kToolbarHeight),
                buildTitle(),
                // buildTitleLine(),
                SizedBox(height: 70.0),
                buildEmailTextField(),
                SizedBox(height: 30.0),
                buildPasswordTextField(context),
                // buildForgetPasswordText(context),
                SizedBox(height: 60.0),
                buildLoginButton(context),
                SizedBox(height: 30.0),
                buildOtherLoginText(),
                buildOtherMethod(context),
                buildRegisterText(context),
              ],
            )
        ),
      )
    );
  }

  Align buildRegisterText(BuildContext context) {
    return Align(
      alignment: Alignment.center,
      child: Padding(
        padding: EdgeInsets.only(top: 10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('没有账号？'),
            GestureDetector(
              child: Text(
                '点击注册',
                style: TextStyle(color: Colors.green),
              ),
              onTap: () {
                //跳转到注册页面
                 Navigator.push(context, MaterialPageRoute(
                     builder: (context){return RegisterPage();}));
              },
            ),
          ],
        ),
      ),
    );
  }

  ButtonBar buildOtherMethod(BuildContext context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: _loginMethod
          .map((item) => Builder(
                builder: (context) {
                  return IconButton(
                      icon: Icon(item['icon'],
                          color: Theme.of(context).iconTheme.color),
                      onPressed: () {
                        ///第三方登录方法
                        Scaffold.of(context).showSnackBar(new SnackBar(
                          content: new Text("${item['title']}登录"),
                          action: new SnackBarAction(
                            label: "取消",
                            onPressed: () {},
                          ),
                        ));
                      });
                },
              ))
          .toList(),
    );
  }

  Align buildOtherLoginText() {
    return Align(
        alignment: Alignment.center,
        child: Text(
          '其他账号登录',
          style: TextStyle(color: Colors.grey, fontSize: 14.0),
        ));
  }

  Align buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: 270.0,
        child: RaisedButton(
          child: Text(
            '登录',
            style: Theme.of(context).primaryTextTheme.headline,
          ),
          color: Colors.black,
          onPressed: validateAndSave,

          shape: StadiumBorder(side: BorderSide()),
        ),
      ),
    );
  }

  Padding buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Align(
        alignment: Alignment.centerRight,
        child: FlatButton(
          child: Text(
            '忘记密码？',
            style: TextStyle(fontSize: 14.0, color: Colors.grey),
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }

  ///密码输入框及验证
  TextFormField buildPasswordTextField(BuildContext context) {
    return TextFormField(
      ///onSaved: (String value) => _password = value,
      obscureText: _isObscure,
      validator: (String value) {
        if (value.isEmpty) {
          _password = "";
          return '请输入密码';
        }else {
          ///验证通过进行赋值
          _password = value;
          return null;
        }
      },
      decoration: InputDecoration(
          labelText: '密码',
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = _isObscure
                      ? Colors.grey
                      : Theme.of(context).iconTheme.color;
                });
              })),
    );
  }

  ///邮箱输入框
  TextFormField buildEmailTextField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: '用户名',
      ),
      validator: (String value) {
        if (value.isEmpty) {
          _email = "";
          return '请输入用户名';
        }else {
          ///验证通过进行赋值
          _email = value;
          return null;
        }
        },
//      validator: (String value) {
//        var emailReg = RegExp(
//            r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
//        if (!emailReg.hasMatch(value)) {
//          return '请输入正确的邮箱地址';
//        }else {
//          return null;
//        }
//      },
      onSaved: (String value) => _email = value,
    );
  }

  Padding buildTitleLine() {
    return Padding(
      padding: EdgeInsets.only(left: 12.0, top: 4.0),
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          color: Colors.black,
          width: 40.0,
          height: 2.0,
        ),
      ),
    );
  }

  Padding buildTitle() {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: Text(
        '登录',
        style: TextStyle(
          fontSize: 42.0
          ),
      ),
    );
  }
}